
#include "precompiled.h"
#include "desktopwidget.h"

#include "engine.h"

class DesktopWidgetPrivate{
	public:
		DesktopWidgetPrivate():file(0), is_changed(false) {}
		~DesktopWidgetPrivate() {}
		QFile* file;
		bool is_changed;
		QString fileName;
		QFileSystemModel *model;
};

DesktopWidget::DesktopWidget(Opl::Core::EntityWidget *parent) :
	Opl::Core::EntityWidget(parent), O_PRIVATE_CREATE(DesktopWidget)
{
	O_D(DesktopWidget);
	setupUi(this);
	declarativeView->setSource(QUrl::fromLocalFile("resources/ui/logo.qml"));
	d->model = new QFileSystemModel;
    d->model->setRootPath(QDir::currentPath());
	filesView->setModel(d->model);
}

DesktopWidget::~DesktopWidget()
{
	O_PRIVATE_DELETE;
}

void DesktopWidget::guiReload()
{
	Engine::instance()->reloadGui();
}

void DesktopWidget::tasksReload()
{
	Engine::instance()->reloadTasks();
}

void DesktopWidget::loadFile()
{
	O_D(DesktopWidget);
	if (d->fileName.isEmpty())
	{ 
		d->fileName = QFileDialog::getOpenFileName(this, tr("Open script file"));
		if (d->fileName.isEmpty()){
			return;
		}
	}

	if (d->file != 0)
	{
		closeFile();
	}

	d->file = new QFile(d->fileName);
	if (!d->file->open(QFile::ReadOnly | QFile::Text)) {
		QMessageBox::warning(this, tr("Recent Files"),
			tr("Cannot read file %1:\n%2.")
			.arg(d->fileName)
			.arg(d->file->errorString()));
		return;
	}

	QTextStream in(d->file);
	QApplication::setOverrideCursor(Qt::WaitCursor);
	QString data = in.readAll();
	textEdit->setPlainText(data);
	QApplication::restoreOverrideCursor();
}

void DesktopWidget::saveFile()
{

}

void DesktopWidget::closeFile()
{
	O_D(DesktopWidget);
	if (d->file != 0)
	{
		return;
	}

	if (d->is_changed)
	{
		QMessageBox::StandardButton code = QMessageBox::question(this, tr("Save Changes"), QString(tr("Save file: %1")).arg(d->file->fileName()), 
			QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
		switch (code)
		{
			case QMessageBox::Yes:
				saveFile();
				break;
			case QMessageBox::Cancel:
				return;
		}		
	}


	d->file->close();
	delete d->file;
	d->file = 0;
	d->is_changed = false;
	d->fileName.clear();
}

void DesktopWidget::changed()
{
	O_D(DesktopWidget);
	d->is_changed = true;
}
